import { store } from "@/store";
import { defineStore } from "pinia";
import ShippingTemplateApi, {
  type ShippingTemplateCreateType,
  type ShippingTemplateListParams,
  type ShippingTemplateType,
} from "@/api/goods/shipping-template";

export const useShippingTemplateStore = defineStore("shipping-template", () => {
  const list = ref<ShippingTemplateType[]>([]);

  const totalCount = ref(0);

  const totalPage = ref(0);

  const loading = reactive({
    list: false,
    create: false,
    update: false,
    delete: false,
  });

  async function fetchShippingTemplateList(params: ShippingTemplateListParams) {
    loading.list = true;
    const response = await ShippingTemplateApi.getShippingTemplateList(params);
    loading.list = false;
    if (response) {
      list.value = response.records;
      totalCount.value = response.total_count;
      totalPage.value = response.total_page;
    }
  }

  async function fetchCreateShippingTemplate(ShippingTemplate: ShippingTemplateCreateType) {
    loading.create = true;
    await ShippingTemplateApi.addShippingTemplate(ShippingTemplate);
    loading.create = false;
  }

  async function fetchUpdateShippingTemplate(ShippingTemplate: Partial<ShippingTemplateType>) {
    loading.update = true;
    await ShippingTemplateApi.updateShippingTemplate(ShippingTemplate);
    loading.update = false;
  }

  async function fetchDeleteShippingTemplate(id: number) {
    loading.delete = true;
    await ShippingTemplateApi.deleteShippingTemplate(id);
    loading.delete = false;
  }

  return {
    list,
    totalCount,
    totalPage,
    loading,
    fetchShippingTemplateList,
    fetchCreateShippingTemplate,
    fetchUpdateShippingTemplate,
    fetchDeleteShippingTemplate,
  };
});

export const useShippingTemplateStoreHook = () => {
  return useShippingTemplateStore(store);
};
